/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package shattered2;

import java.awt.BorderLayout;
import java.awt.Toolkit;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.*;

/**
 *
 * @author 10135228
 */
public class ImageServer {
    
    int amount = 15900;
    private String verzeichnis = "C:/manypieces";
    private JProgressBar pb = new JProgressBar(JProgressBar.HORIZONTAL, 0, amount);
    private JTextArea ta = new JTextArea();
    JPanel pbPanel = new JPanel();
    JFrame myFrame = null;
    
    public static void main(String[] args) {
        new ImageServer();
    }

    public ImageServer() {
        
        myFrame = new JFrame("Image Server");
        myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myFrame.setSize(300, 200);
        myFrame. setLayout(new BorderLayout());
        myFrame.getContentPane().add(pb,BorderLayout.NORTH);
        pb.setStringPainted(true);
        myFrame.getContentPane().add(new JScrollPane(ta, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER),BorderLayout.CENTER);
        ta.setEditable(false);
        myFrame.getContentPane().add(pbPanel,BorderLayout.SOUTH);
        pbPanel.setLayout(new BoxLayout(pbPanel, BoxLayout.Y_AXIS));
        myFrame.setVisible(true);
        final ImageIcon[] images = readImages(verzeichnis);
        
        ServerSocket mySocket = null;
        try {
            mySocket = new ServerSocket(22222);
            log("Server ready...");
            pb.setString("Server ready");  
            pb.setVisible(false);
        } catch (IOException ex) {
            Logger.getLogger(ImageServer.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        while (true) {            
            try {
                final Socket client = mySocket.accept();
                new Thread(){

                    @Override
                    public void run() {
                        ObjectOutputStream out = null;
                        BufferedReader in =  null;
                        try {
                            out = new ObjectOutputStream(client.getOutputStream());
                            in = new BufferedReader(new InputStreamReader(client.getInputStream()));
                            int count = Integer.decode(in.readLine());
                            log("Requested: "+count+" images");
                            JProgressBar pbl = new JProgressBar(JProgressBar.HORIZONTAL, 0, count-1);
                            pbPanel.add(pbl);
                            myFrame.validate();
                            myFrame.repaint();
                            for (int i = 0; i < count && i < amount; i++) {
                                out.writeObject(images[i]);                      
                                pbl.setValue(i);
                            }                          
                            log("Successfully sent!");
                            pbPanel.remove(pbl);
                            myFrame.validate();
                            myFrame.repaint();
                        } catch (IOException ex) {
                            Logger.getLogger(ImageServer.class.getName()).log(Level.SEVERE, null, ex);
                            log("Error while sending!");
                        } finally {
                            try {
                                out.flush();
                                out.close();
                                in.close();    
                            } catch (IOException ex) {
                                Logger.getLogger(ImageServer.class.getName()).log(Level.SEVERE, null, ex);
                            }                           
                        }
                    }                    
                }.start();
                    
 
            } catch (IOException ex) {
                Logger.getLogger(ImageServer.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    
    
    private ImageIcon[] readImages(String locString) {
        
        log("Starting reading images...");
        long timeStart = System.currentTimeMillis();
        Path location = Paths.get(locString);
        try{
            DirectoryStream<Path> imageFileStream = Files.newDirectoryStream(location, "*.png");
            ImageIcon[] tempArray = new ImageIcon[amount];
            int i = 0;
            for(Path p : imageFileStream){
                //System.out.println(p.getFileName());
                tempArray[i] = new ImageIcon(ImageIO.read(p.toUri().toURL()));
                pb.setValue(++i);
                if(i==amount) break;
                
            }
            //pb.setString("done");
            long timeEnd = System.currentTimeMillis();
            String format = String.format("%%0%dd", 2);  
            long elapsedTime = (timeEnd-timeStart) / 1000;  
            String seconds = String.format(format, elapsedTime % 60);  
            String minutes = String.format(format, (elapsedTime % 3600) / 60);  
            String hours = String.format(format, elapsedTime / 3600);  
            String time =  hours + ":" + minutes + ":" + seconds; 
            Toolkit.getDefaultToolkit().beep();
            log("Done reading images in "+time);
            return tempArray;
        }catch(IOException e){
            log("ERROR reading images!");
        }
        return null;
    }  
    
    private void log(String text){
        
        SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
        
        ta.append(df.format(new Date())+" ");    
        ta.append(text);
        ta.append("\n");
        ta.setCaretPosition(ta.getText().length());
    }
    
}
